package com.tjl.warehouse.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tjl.warehouse.annotation.AuthToken;
import com.tjl.warehouse.common.ErrorCode;
import com.tjl.warehouse.common.R;
import com.tjl.warehouse.exception.BusinessException;
import com.tjl.warehouse.exception.ThrowUtils;
import com.tjl.warehouse.model.AuthInfo;
import com.tjl.warehouse.model.MyPage;
import com.tjl.warehouse.model.Role;
import com.tjl.warehouse.model.UserInfo;
import com.tjl.warehouse.model.dto.AssignRoleReq;
import com.tjl.warehouse.model.dto.UserDto;
import com.tjl.warehouse.service.AuthInfoService;
import com.tjl.warehouse.service.RoleService;
import com.tjl.warehouse.service.UserInfoService;
import com.tjl.warehouse.utils.DigestUtil;
import com.tjl.warehouse.utils.JWTUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author Tang
 * @createDate 2024/5/12
 */
@RestController
@Slf4j
@Tag(name = "用户接口")
@AuthToken
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserInfoService userService;
    @Resource
    private AuthInfoService authService;
    @Resource
    private RoleService roleService;

    @GetMapping("/auth-list")
    public R<List<AuthInfo>> getAuthList(@RequestHeader String token){

        int userId = JWTUtils.getUserIdFromToken(token);

        return R.success(authService.getAuthInfo(userId));
    }

    @GetMapping("/user-auth")
    public R<List<AuthInfo>> getUserAuthById(Integer userId){
        return R.success(authService.getAuthInfo(userId));
    }


    @GetMapping("/user-list")
    public R<MyPage<UserInfo>> getUserList( UserDto userDto,
                    MyPage<UserInfo> myPage){
        //检查page参数
        if (myPage.getPageSize() == 0 || myPage.getPageSize() > 100){
            myPage.setPageSize(10L);
        }
        if (myPage.getPageNum() <= 0 ){
            myPage.setPageSize(1L);
        }

        UserInfo userInfo = new UserInfo();

        //这段代码导致模糊查询无效 原因不明 userinfo能正常被BeanUtils赋值，但就是无法查询出结果
//        boolean allBlank = StringUtils.isAllBlank(userDto.getUserCode(), userDto.getUserName(),
//                userDto.getUserType(), userDto.getUserState());
//        //检查userDto参数是否为空
//        if(!allBlank){
//            BeanUtils.copyProperties(userDto,userInfo);
//        }
        if (StringUtils.isNotBlank(userDto.getUserCode())){
            userInfo.setUserCode(userDto.getUserCode());
        }
        if (StringUtils.isNotBlank(userDto.getUserName())){
            userInfo.setUserName(userDto.getUserName());
        }
        if (StringUtils.isNotBlank(userDto.getUserType())){
            userInfo.setUserType(userDto.getUserType());
        }
        if (StringUtils.isNotBlank(userDto.getUserState())){
            userInfo.setUserState(userDto.getUserState());
        }


        //分页查询
        MyPage<UserInfo> userPage = userService.getUserPage(userInfo, myPage);
        return R.success(userPage);

    }

    @PostMapping("/addUser")
    public R<String> addUser(@RequestBody UserInfo userDto,@RequestHeader String token){
        if (StringUtils.isBlank(userDto.getUserCode())){
            return R.error(ErrorCode.PARAMS_ERROR,"用户编码不能为空");
        }
        if (StringUtils.isBlank(userDto.getUserName())){
            return R.error(ErrorCode.PARAMS_ERROR,"用户名称不能为空");
        }
        if (StringUtils.isBlank(userDto.getUserPwd())){
            return R.error(ErrorCode.PARAMS_ERROR,"用户密码不能为空");
        }


        if (userService.addUser(userDto,JWTUtils.getUserIdFromToken(token))){
            return R.success("添加成功");
        }else {
            return R.error(ErrorCode.SYSTEM_ERROR,"添加失败");
        }
    }

    @PutMapping({"/updateUser", "/updateState"})
    public R<String> updateUser(@RequestBody UserInfo userInfo,@RequestHeader String token){
        if (userInfo == null){
            return R.error(ErrorCode.PARAMS_ERROR,"参数错误");
        }
        if (userInfo.getUserId() == null){
            return R.error(ErrorCode.PARAMS_ERROR,"用户id不能为空");
        }

        if (userService.updateUser(userInfo,JWTUtils.getUserIdFromToken(token))){
            return R.success("修改成功");
        }else {
            return R.error(ErrorCode.SYSTEM_ERROR,"修改失败");
        }
    }

    //删除单个用户
    @DeleteMapping("/deleteUser/{id}")
    public R<String> deleteUser(@PathVariable("id") Integer id){
        if (id == null){
            return R.error(ErrorCode.PARAMS_ERROR,"用户id不能为空");
        }
        if (userService.removeById(id)){
            return R.success("删除成功");
        }else {
            return R.error(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
    }

    //批量删除
    @DeleteMapping("/deleteUserList")
    public R<String> deleteUserList(@RequestBody List<Integer> idList){
        if (idList == null || idList.isEmpty()){
            return R.error(ErrorCode.PARAMS_ERROR);
        }
        if (userService.removeByIds(idList)){
            return R.success("删除成功");
        }else {
            return R.error(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
    }

    //重置密码
    @PutMapping("/updatePwd/{id}")
    public R<String> updatePwd(@PathVariable("id") Integer id){
        UserInfo byId = userService.getById(id);
        ThrowUtils.throwIfParams(byId == null,"用户不存在");
        //重置密码为123456
        byId.setUserPwd(DigestUtil.hmacSign("123456"));
        return R.success("重置成功");
    }

    //跟据用户id获取角色
    @GetMapping("/user-role-list/{id}")
    public R<List<Role>> getUserRoleList(@PathVariable("id") Integer id){

        if (id == null || id < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        List<Role> userRoleById = roleService.getUserRoleById(id);
        return R.success(userRoleById);
    }

    @PutMapping("/assignRole")
    public R<String> assignRole(@RequestBody AssignRoleReq assignRole){
        //检查参数
        ThrowUtils.throwIfParams(assignRole == null);

        boolean b = userService.updateUserRole(assignRole);
        if (b){
            return R.success("分配成功");
        }else {
            return R.error(ErrorCode.SYSTEM_ERROR,"分配失败");
        }

    }
}
